#!/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
author : GQ
project : ApiTestPlatform
date : 2021/11/17
"""

import requests
import json
import sys

# sys.path.append('../')  # 在上一级找相应的其他python包或者文件

# 隐藏ssl报错信息
requests.packages.urllib3.disable_warnings()

class HttpHandle:
    '''封装requests方法'''

    def __init__(self):
        '''requests库的session对象能够帮我们跨请求保持某些参数，也会在同一个session实例发出的所有请求之间保持cookies。'''
        self.http = requests.session()  # 开启一个session会话
        self.headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
            'accept-encoding': 'gzip'}
        self.http.headers = self.headers  # 设置请求头

    def get(self, url, params=None, data={},**kwargs):
        try:
            if "headers" not in kwargs:
                kwargs['headers'] = self.headers
            res = self.http.get(
                url, params=params, verify=False,data=data, **kwargs)  # verify=False,将verify 设置为 False，Requests 将忽略对 SSL 证书的验证
        except Exception as err:
            print(err)
            assert False
        self.respone_print('get', res, params)
        dic_res = json.loads(res.content.decode('utf-8', 'ignore'))  # 字符转字典
        return dic_res

    def post(self, url, data=None, convert_to_json=False, **kwargs):
        '''
        :return 字典型响应数据
        默认入参不转字符串
        '''
        # 加上ensure_ascii=False,保证dumps之后的结果里所有的字符都能够被ascii表示,否则按参数默认值True，
        try:
            if convert_to_json:
                # 转为json
                data = json.dumps(data, ensure_ascii=True).encode('utf-8')
            if 'headers' not in kwargs:
                kwargs['headers'] = self.headers
            res = requests.session().post(url, data=data, verify=False, **kwargs)
        except Exception as err:
            print(err)
            assert False  # 必须加上否则没有退出机制，return 报错
        self.respone_print('post', res, data)
        dic_res = json.loads(res.content.decode('utf-8', 'ignore'))  # 字符转字典
        return dic_res

    def put(self, url, data=None, convert_to_json=False, **kwargs):
        try:
            if convert_to_json:
                # 转为json字符串 如果dict包含有汉字，一定加上ensure_ascii=False。经过json.dumps(dict)，拿到的str看起来和dic长得很像，但实际含义很不一样。
                data = json.dumps(data, ensure_ascii=False).encode('utf-8')
            # print(data)
            if "headers" not in kwargs:
                kwargs['headers'] = self.headers
            res = self.http.put(url, data=data, verify=False, **kwargs)
        except Exception as err:
            print(err)
            assert False
        self.respone_print('put', res, data)
        dic_res = json.loads(res.content.decode('utf-8', 'ignore'))  # 字符转字典
        return dic_res

    def delete(self, url, data=None, **kwargs):
        """如果data是str则不需要转换，直接使用,如果data是非str类型则尝试转为json"""
        try:
            if "headers" not in kwargs:
                kwargs['headers'] = self.headers
            if data:
                if not isinstance(data, str):
                    data = json.dumps(data, ensure_ascii=False).encode('utf-8')
                res = self.http.delete(url, data=data, verify=False, **kwargs)
            else:
                res = self.http.delete(url, **kwargs)
        except Exception as err:
            print(err)
            assert False
        self.respone_print('delete', res, data)
        dic_res = json.loads(res.content.decode('utf-8', 'ignore'))  # 字符转字典
        return dic_res

    def respone_print(self, method, res, argument):
        if res.status_code == 200:
            print('发送%s请求: %s\n请求参数: %s\n服务器返回: %s' % (method, res.url, argument, res.status_code))
        else:
            print('发送%s请求: %s\n请求参数: %s\n服务器返回: %s\n返回内容:\n%s' % (
                method, res.url, argument, res.status_code, res.content.decode('utf-8', 'ignore')))
        try:
            if len(res.content) > 0:
                if 'xml' in res.headers['Content-Type'] or 'execl' in res.headers['Content-Type']:
                    xresult = res.content.decode('utf-8', 'ignore')
                    print('返回xml: %s' % xresult)
                else:
                    jresult = json.loads(res.content.decode('utf-8', 'ignore'))
                    print('返回json: %s' % jresult)

        except ValueError as err:
            print(err)
            assert False

    # 验证key是否有效
    def key_is_valid(self):
        pass

    def turn_goods_path(self, goods_id):
        '''拼凑小黄车商品路径'''
        s = str(goods_id)
        l = len(s)
        k = int(l / 3)
        goods_str = ''
        if l % 3 == 0:
            for i in range(k):
                temp = s[i * 3:(i + 1) * 3]
                goods_str = goods_str + temp + '/'
            goods_str = '/' + goods_str
        else:
            goods_str = s[0:l - k * 3]
            for i in range(k):
                temp = s[(l - k * 3) + i * 3:(l - k * 3) + (i + 1) * 3]
                goods_str = goods_str + '/' + temp
            goods_str = '/' + goods_str + '/'
        return goods_str


if __name__ == '__main__':
    pass
    # user_login, user_pass = ('13521414503', 't654321')
    # print('22')
